<?php

namespace app\service;

use app\exception\ParameterException;
use think\facade\Cache;
class CodeService
{
    protected  $cache;
    private $prefix = 'code_';
    public function __construct()
    {
        $this->cache = Cache::store('file');
    }

    public function checkCode($phone, $code)
    {
        if($this->cache->get($this->prefix.$phone) == $code){
            return true;
        }else{
            return false;
        }

    }

    public function getCode()
    {
        //生成随机6位验证码
        return str_pad(strval(random_int(0, 999999)), 6, '0', STR_PAD_LEFT);
    }

    public function setCode($phone, $code)
    {

        if(!$phone) throw new ParameterException("请输入手机号!");
        if(!isMobile($phone)) throw new ParameterException("手机号有误!");
        //if($this->cache->get($this->prefix.$phone)) throw new  ParameterException("请问频繁操作!");

        //验证手机号是否合法
        if(!preg_match('/^1[3-9]\d{9}$/', $phone) === 1) throw new ParameterException("手机号有误!");

        //设置验证码缓存
        return $this->cache->set($this->prefix.$phone, $code,80);
    }

    public function deleteCode($phone)
    {
        return $this->cache->delete($this->prefix.$phone);
    }
}
